using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {

    private GameObject[] obs;
    private Vector3 moveDirection;
    
    // Use this for initialization
    void Start()
    {
        obs = GameObject.FindGameObjectsWithTag("Player");
    }
    
    // Update is called once per frame
    void Update()
    {
		if(Network.isServer){
	        GameObject closest = FindClosestEnemy(gameObject);
	        transform.LookAt(closest.transform);
	        moveDirection = transform.TransformDirection(Vector3.forward);
	        moveDirection.Normalize();
	        this.transform.position += moveDirection;
			networkView.RPC("UpdateEnemyPosition",RPCMode.Server,transform.position,transform.rotation);
		}
    }
    
    // Find the closest enemy (I mean player)
    public static GameObject FindClosestEnemy(GameObject controlled)
    {
        GameObject[] gos;
        gos = GameObject.FindGameObjectsWithTag("Player");
        GameObject closest = null;
        float distance = Mathf.Infinity;
        Vector3 position = controlled.transform.position;
        foreach (GameObject go in gos)
        {
            Vector3 diff = go.transform.position - position;
            float curDistance = diff.sqrMagnitude;
            curDistance =  Mathf.Sqrt(curDistance);
            if (curDistance < distance)
            {
                closest = go;
                distance = curDistance;
            }
        }
    return closest;
    }
	[RPC]
	void UpdateEnemyPosition(Vector3 pos, Quaternion rot){
		transform.position = pos;
		transform.rotation = rot;
	}
}